package com.fudan.biz.visualize.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.elasticsearch.index.query.QueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fudan.biz.data.service.FieldMetaService;
import com.fudan.biz.visualize.entity.ChartSetting;
import com.fudan.biz.visualize.service.ChartSettingService;
import com.fudan.es.entity.Metric;
import com.fudan.es.entity.Metric.MetricType;
import com.fudan.es.search.QueryService;
import com.fudan.es.entity.QueryPack;
import com.fudan.es.service.AggsService;
import com.fudan.framework.base.BaseController;
import com.fudan.framework.entity.ResponseMsg;

/**
 * @ClassName: ChartController
 * @Description: TODO
 * @Author: DavidDong
 * @Date: 2019/4/11 22:47
 **/
@Controller
@RequestMapping(value = "/biz/visualize")
public class ChartController extends BaseController {

	@Autowired
	private AggsService aggsService;
	@Autowired
	private FieldMetaService fieldMetaService;
	@Autowired
	private QueryService queryService;
	@Autowired
	private ChartSettingService chartSettingService;

	@RequestMapping("/draw/pie")
	@ResponseBody
	public ResponseMsg drawPie(HttpServletRequest request) {
		try {
			Map<String,Object> ret = null;
			String metric = request.getParameter("metric");
			String metricField = request.getParameter("metric_field");
			String dsId = request.getParameter("ds_id");
			String dimension = request.getParameter("dimensions");
			if("count".equals(metric)) {
				ret = aggsService.countByFields(dsId, dimension.split(","));
			}
			if("sum".equals(metric)) {
				ret = aggsService.sumByField(dsId,dimension,metricField);
			}
			if("avg".equals(metric)) {
				ret = aggsService.avgByField(dsId, dimension, metricField);
			}
			return ResponseMsg.build().putData(ret);
		}catch(Exception e) {
			e.printStackTrace();
			return ResponseMsg.build(SYSTEM_ERROR_CODE, ERROR);
		}
	}
	@RequestMapping("/draw")
	@ResponseBody
	public ResponseMsg test(HttpServletRequest request) {
		String metrics = request.getParameter("metrics");
		if(metrics == null) {
			return ResponseMsg.build(SYSTEM_ERROR_CODE, "没有指定指标");
		}
		String[] metricString = metrics.split(",");
		String rex = "([^(]+)[(]([0-9]*)[)]";
		List<Metric> metricList = new ArrayList<Metric>();
		for (String string : metricString) {
			Pattern pattern = Pattern.compile(rex);
			Matcher matcher = pattern.matcher(string);
			if(matcher.find()) {
				Metric metric = null;
				if(matcher.group(2) == null || "".equals(matcher.group(2))) {
					metric = Metric.build(MetricType.valueOf(matcher.group(1).toUpperCase()), null);
				}else {
					metric = Metric.build(MetricType.valueOf(matcher.group(1).toUpperCase()), fieldMetaService.get(matcher.group(2)));
				}
				metricList.add(metric);
			}
		}
		String dsId = request.getParameter("ds_id");
		String dimension = request.getParameter("dimension");
		String dimensionSizeStr = request.getParameter("dimension_size");
		String querys = request.getParameter("querys");
		int dimensionSize = 10;
		if(dimensionSizeStr!=null&&dimensionSizeStr.matches("[0-9]+")) {
			dimensionSize = Integer.parseInt(dimensionSizeStr);
		}
		try {
			List<QueryPack> queryList = queryService.buildQueryPacks(querys);
			QueryBuilder queryBuilder = queryService.buildQuery(queryList);
			return ResponseMsg.build().putData(aggsService.aggs(dsId,metricList,dimension,dimensionSize, queryBuilder));
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMsg.build(SYSTEM_ERROR_CODE, ERROR);
		}
	}

	@RequestMapping("/draw/req")
	@ResponseBody
	public String testq(HttpServletRequest request) {
		String metrics = request.getParameter("metrics");
		if(metrics == null) {
			return "指标没有设置";
		}
		String[] metricString = metrics.split(",");
		String rex = "([^(]+)[(]([0-9]*)[)]";
		List<Metric> metricList = new ArrayList<Metric>();
		for (String string : metricString) {
			Pattern pattern = Pattern.compile(rex);
			Matcher matcher = pattern.matcher(string);
			if(matcher.find()) {
				System.out.println(matcher.group(1)+" - "+matcher.group(2));
				Metric metric = null;
				if(matcher.group(2) == null || "".equals(matcher.group(2))) {
					metric = Metric.build(MetricType.valueOf(matcher.group(1).toUpperCase()), null);
				}else {
					metric = Metric.build(MetricType.valueOf(matcher.group(1).toUpperCase()), fieldMetaService.get(matcher.group(2)));
				}
				metricList.add(metric);
			}
		}
		String dsId = request.getParameter("ds_id");
		String dimension = request.getParameter("dimension");
		String filters = request.getParameter("filters");
		try {
			String dimensionSizeStr = request.getParameter("dimension_size");
			int dimensionSize = 10;
			if(dimensionSizeStr!=null&&dimensionSizeStr.matches("[0-9]+")) {
				dimensionSize = Integer.parseInt(dimensionSizeStr);
			}
			List<QueryPack> querys = queryService.buildQueryPacks(filters);
			QueryBuilder queryBuilder = queryService.buildQuery(querys);
			return aggsService.getRequest(dsId,metricList,dimension,dimensionSize, queryBuilder);
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

    @RequestMapping("/pie")
    public String showPie() {
        return "biz/visualize/pie";
    }

    @RequestMapping("/chart")
    public ModelAndView chart(HttpServletRequest request) {
    	String id = request.getParameter("id");
    	if(id == null) {
    		return new ModelAndView("biz/visualize/chart");
    	}else {
    		ChartSetting chartSetting =  chartSettingService.get(id);
    		ModelAndView view = new ModelAndView("biz/visualize/chart");
    		view = view.addObject("chartId",chartSetting.getId().toString());
    		view.addObject("chartName",chartSetting.getChartName());
    		view.addObject("chartDsId",chartSetting.getChartDsId().toString());
    		view.addObject("chartDsName",chartSetting.getChartDsName());
    		view.addObject("chartMetrics",chartSetting.getChartMetrics());
    		view.addObject("chartDimensions",chartSetting.getChartDimensions());
    		view.addObject("chartQuerys",chartSetting.getChartQuerys());
    		view.addObject("chartCustoms",chartSetting.getChartCustoms());

    		return view;
    	}
    }

    @RequestMapping("/bar")
    public String showBar() {
        return "biz/visualize/bar";
    }

    @RequestMapping("/line")
    public String showLine() {
        return "biz/visualize/line";
    }

	@RequestMapping("/chart/show")
	public String chartShow(HttpServletRequest request) {
		String id = request.getParameter("id");
		if(id != null){
			ChartSetting chartSetting =  chartSettingService.get(id);
			request.setAttribute("chartId",chartSetting.getId());
			request.setAttribute("chartName",chartSetting.getChartName());
			request.setAttribute("chartDsId",chartSetting.getChartDsId());
			request.setAttribute("chartDsName",chartSetting.getChartDsName());
			request.setAttribute("chartMetrics",chartSetting.getChartMetrics());
			request.setAttribute("chartDimensions",chartSetting.getChartDimensions());
			request.setAttribute("chartQuerys",chartSetting.getChartQuerys());
			request.setAttribute("chartCustoms",chartSetting.getChartCustoms());
		}
		return "biz/visualize/chart";
	}
}
